class ArticlesController < ApplicationController
  # http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]

  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    # render plain: params[:article].inspect
    @article = Article.new(article_params)

    image_path = File.expand_path(File.dirname(__FILE__) + '/../..') + "/public/images" + "/3.png"
    # puts image_path
    #
    # params[:avatar] = parse_foo_file_data(params[:avatar]) if params[:avatar]

    tmpf = params[:article][:avatar].tempfile.to_path.to_s
    # data = File.readlines(tmpf)
    data = params[:article][:avatar].tempfile.read
    File.write(image_path, data)
    # img = File.new(image_path, "w+")
    # if img
    #   img.syswrite(data)
    # end
    # img.close

    # @article.avatar = params[:foo_file]
    # tmpf = params[:article][:avatar].tempfile.to_path.to_s
    # FileUtils.mv(tmpf, image_path)

    render json: {url: params[:article][:avatar].tempfile.to_path.to_s}

    # if @article.save
    #   redirect_to @article
    # else
    #   render 'new'
    # end
  end

  def parse_foo_file_data(foo_file_data)
    @tempfile = Tempfile.new('item_foo_file')
    @tempfile.binmode
    @tempfile.write Base64.decode64(foo_file_data.read)
    @tempfile.rewind

    uploaded_file = ActionDispatch::Http::UploadedFile.new(
      tempfile: @tempfile,
      original_filename: foo_file_data.original_filename
    )

    uploaded_file.content_type = foo_file_data.content_type
    # uploaded_file
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    redirect_to articles_path
  end

  private
  def article_params
    params.require(:article).permit(:title, :text, :avatar)
  end
end
